package it.spredt.api;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;

/**
 * Class for enabling your application with spredt.it
 * 
 * @author mbrehme
 * 
 */
public class SpredtEnabler {
	
	private static Intent	installIntent;
	private static Intent	spredtPutIntent;
	
	/**
	 * Find out if spred.it is installed
	 * 
	 * @param context
	 *            - {@link Context} needed to find the receiver for the PUT intent.
	 * @return {@link Boolean} true if spred.it is installed
	 */
	public static boolean isInstalled(Context context) {
		
		if (spredtPutIntent == null)
			spredtPutIntent = new Intent(SpredtConstants.INTENT_ACTION_PUSH);
		
		List<ResolveInfo> pkgAppsList = context.getPackageManager().queryIntentActivities(spredtPutIntent, 0);
		
		return pkgAppsList != null && pkgAppsList.size() > 0;
	}
	
	/**
	 * The Intent to find spredt.it in the market
	 * 
	 * @return the {@link Intent} for finding spredt.it in the market
	 */
	public static Intent getMarketIntent() {
		
		if (installIntent == null)
			installIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(SpredtConstants.MARKET_URL));
		
		return installIntent;
	}
	
	/**
	 * Helper method for reading user data. (e.g. username)
	 * 
	 * @param context
	 * @param columns
	 *            <ul>
	 *            <li>{@link SpredtConstants#CONTENT_PROVIDER_USERNAME}</li>
	 *            </ul>
	 * @return
	 */
	public static Map<String, String> getUserData(Context context, String... columns) {
		Map<String, String> values = new HashMap<String, String>();
		Cursor query = context.getContentResolver().query(SpredtConstants.CONTENT_PROVIDER_URI, columns, null, null, null);
		query.moveToFirst();
		for (String column : columns) {
			int columnIndex = query.getColumnIndex(column);
			if (columnIndex >= 0)
				values.put(column, query.getString(columnIndex));
		}
		query.close();
		return values;
	}
	
}
